<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Redis;
use DB;

class CheckWxLogin
{

    public function handle($request, Closure $next)
    {
        if (!((request('xcx_openid') || request('wx_openid')) && request('sid'))) {
            return error('未授权访问');
        }
        $GLOBALS['xcx_openid'] = request('xcx_openid', '');
        $GLOBALS['wx_openid'] = request('wx_openid', '');
        $GLOBALS['shop_id'] = request('sid', 0);
        if ($GLOBALS['xcx_openid'] && $GLOBALS['shop_id']) {
            $info = $this->getInfoByXcxOpenId($GLOBALS['xcx_openid'], $GLOBALS['shop_id']);
        }
        if ($GLOBALS['wx_openid'] && $GLOBALS['shop_id']) {
            $info = $this->getInfoByWxOpenId($GLOBALS['wx_openid'], $GLOBALS['shop_id']);
        }
        if (!$info) {
            return error('未授权访问');
        }
        $GLOBALS['mid'] = $info['mid'];
        $GLOBALS['admin_id'] = $info['aid'];
        return $next($request);
    }

    public function getInfoByXcxOpenId($xcx_openid, $shop_id)
    {
        $key = $xcx_openid . '_' . $shop_id;
        $info = Redis::get($key);
        if (!$info) {
            $info = DB::table('member')->select('id as mid', 'shop_id as sid', 'xcx_openid', 'nickname', 'avatarurl', 'admin_id as aid', 'mobile','status','buy_min','buy_max','worker_id')
                ->where('xcx_openid', $xcx_openid)->where('shop_id', $shop_id)->first();
            if (!$info) {
                return false;
            }
            $info = serialize(object_to_array($info));
            Redis::setex($key, 3600, $info);
        }
        return unserialize($info);
    }

    public function getInfoByWxOpenId($wx_openid, $shop_id)
    {
        $key = $wx_openid . '_' . $shop_id;
        $info = Redis::get($key);
        if (!$info) {
            $info = DB::table('member')->select('id as mid', 'shop_id as sid', 'wx_openid', 'nickname', 'avatarurl', 'admin_id as aid', 'mobile','status','buy_min','buy_max','worker_id')
                ->where('wx_openid', $wx_openid)->where('shop_id', $shop_id)->first();
            if (!$info) {
                return false;
            }
            $info = serialize(object_to_array($info));
            Redis::setex($key, 3600, $info);
        }
        return unserialize($info);
    }
}

